package com.park.oss.web.mobile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.park.oss.model.CarPlace;
import com.park.oss.model.Gate;
import com.park.oss.model.Park;
import com.park.oss.model.Payment;
import com.park.oss.model.Place;
import com.park.oss.model.PlaceRent;
import com.park.oss.model.PlaceRentRule;
import com.park.oss.model.SysUser;
import com.park.oss.model.UserBalance;
import com.park.oss.service.CarPlaceService;
import com.park.oss.service.GateService;
import com.park.oss.service.ParkSearchService;
import com.park.oss.service.ParkService;
import com.park.oss.service.PaymentService;
import com.park.oss.service.PlaceService;
import com.park.oss.service.RentService;
import com.park.oss.service.UserService;
import com.park.oss.util.HttpUtil;
import com.park.oss.util.JsonResult;
import com.park.oss.util.ParkUtil;
import com.park.oss.vo.FreePark;
import com.park.oss.vo.PlaceVo;

@Controller
public class UserController {
	@Autowired
	UserService userService;
	@Autowired
	ParkService parkService;
	
	@Autowired
	PlaceService placeService;
	
	@Autowired
	ParkSearchService searchService;
	
	@Autowired
	PaymentService paymentService;
	@Autowired
	CarPlaceService carPlaceService;
	
	@Autowired
	RentService rentService;
	
	@Autowired
	GateService gateService;
	
	
	
	@RequestMapping(value = "/mobile/user/login.html", method = RequestMethod.POST)
	public ModelAndView login(String mobile, String password, String useType, String location,HttpServletRequest req) {
		ModelAndView view = null;
		req.getSession().setAttribute("location", location);
		SysUser user = userService.getUser(mobile, password);
		if (user == null) {
			user = userService.addUser(mobile, password);
			req.getSession().setAttribute("user", user);
			view = new ModelAndView("/mobile/user/info.btl");
		} else {
			req.getSession().setAttribute("user", user);
			if(user.getName()==null){
				view = new ModelAndView("/mobile/user/info.btl");
			}else{
				if (useType == null) {
					// 附近车场
					view = new ModelAndView("forward:/mobile/rent/search.html");
							
				} else {
					// 我的收入
					view = new ModelAndView("forward:/mobile/user/myIncoming.html");
			
					
				}
			}
			
		}
		req.getSession().setAttribute("useType", "on".equals(useType)?1:0);
//		if(1==1) throw new RuntimeException("error !!");
		return view;
	}
	
	

	@RequestMapping(value = "/mobile/user/logout.html", method = RequestMethod.GET)
	public ModelAndView logout(String mobile, String password, String useType, String location,HttpServletRequest req) {
		ModelAndView view = null;
		req.getSession().removeAttribute("location");
		req.getSession().removeAttribute("user");
		req.getSession().removeAttribute("useType");
		view = new ModelAndView("redirect:/mobile/");
		return view;
	}
	
	@RequestMapping(value = "/mobile/rent/search.html")
	public ModelAndView search( HttpServletRequest req) {
		ModelAndView view = null;
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		String loc = (String)req.getSession().getAttribute("location");
		if(loc!=null){
			Double[] locs = ParkUtil.getLoc(loc);
			List<FreePark> parks = searchService.searchFreePark(user,locs[0], locs[1],ParkUtil.today());
			view = new ModelAndView("/mobile/rent/search.btl");
			view.addObject("list", parks);
		}else{
			view.addObject("noloc", true);
		}
		
		return view;
	}
	
	@RequestMapping(value = "/mobile/rent/searchRefresh.html")
	public ModelAndView searchRefresh( HttpServletRequest req) {
		//实际上，可以同search方法合并
		ModelAndView view = null;
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		String loc = (String)req.getSession().getAttribute("location");
		Double[] locs = ParkUtil.getLoc(loc);
		List<FreePark> parks = searchService.searchFreePark(user,locs[0], locs[1],ParkUtil.today());
		view = new ModelAndView("/mobile/rent/search.btl#parkList");
		view.addObject("list", parks);
		return view;
	}
	
	@RequestMapping(value = "/mobile/rent/doRent.html", produces = "text/html;charset=UTF-8")
	public @ResponseBody String doRent( Integer parkId,HttpServletRequest req,HttpServletResponse rsp) {
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		JsonResult result = new JsonResult();
//		rsp.setContentType("application/x-json;charset=UTF-8");
		CarPlace cp = paymentService.getAvaibleRent(user.getId());
		
		
		
		if(cp==null){
			Integer id =  paymentService.doRent(user, parkId);
			if(id==-1){
				result.setSuccess(false);
				result.setObj("没有可用车位");
			}else if(id==-2){
				result.setSuccess(false);
				result.setObj("只有自己车位空闲，没有可用车位");
			}else{
				cp = this.carPlaceService.getCarPlace(id.longValue());
				syncOrder(cp);
				result.setObj(ParkUtil.encode(id));
			}
			
		}else{
//			syncOrder(cp);
			result.setObj(ParkUtil.encode(cp.getId()));
		}
		
		
		//为啥是
		return result.json();
		
	}
	
	@RequestMapping(value = "/mobile/rent/unRent.html")
	public  ModelAndView unRent( Integer parkId,HttpServletRequest req) {
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		JsonResult result = new JsonResult();
		CarPlace cp = paymentService.getAvaibleRent(user.getId());
		
		
		if(cp!=null){
			 paymentService.unRent(cp,user, parkId);
			 
		}
		ModelAndView view = new ModelAndView("forward:/mobile/rent/search.html");
		return view;
		
	}
	
	@RequestMapping(value = "/mobile/user/myMatrix.html")
	public ModelAndView myMatrix(HttpServletRequest req) {
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		JsonResult result = new JsonResult();
		CarPlace cp = paymentService.getAvaibleRent(user.getId());
		ModelAndView view = new ModelAndView("/mobile/rent/myMatrix.btl");
		if(cp!=null){
			
			Integer parkId = cp.getParkId();
			Park park = parkService.getPark(parkId);
			view.addObject("carPlace",cp);
			view.addObject("park",park);
			
		}else{
			//被其他人订购了
			return  new ModelAndView("forward:/mobile/rent/search.html");  
		}
		return view;
		
	
	}
	
	
	@RequestMapping(value = "/mobile/user/getMatrixImg.do")
	public @ResponseBody void getMatrix( String id,HttpServletRequest req,HttpServletResponse rsp) {
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		rsp.setContentType("image/jpeg ");
		try {
			ParkUtil.genMatrixImage(ParkUtil.encode(Long.parseLong(id)), rsp.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	
	}
	
	/*用来测试的*/
	@RequestMapping(value = "/mobile/rent/doEnter.html")
	public ModelAndView doEnter( Integer parkId,HttpServletRequest req) {
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		paymentService.doEnter(user, parkId);
		ModelAndView view = new ModelAndView("forward:/mobile/rent/search.html");
		return view;
	}
	
	/*用来测试的*/
	@RequestMapping(value = "/mobile/rent/doPay.html")
	public ModelAndView doPay( Integer parkId,HttpServletRequest req) {
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		CarPlace cp = paymentService.doPay(user, parkId);
		this.syncPay(cp);
		ModelAndView view = new ModelAndView("forward:/mobile/user/myMatrix.html");
		return view;

	}
	
	@RequestMapping(value = "/mobile/rent/getPayInfo.html")
	public @ResponseBody String getPayInfo( Integer parkId,HttpServletRequest req,HttpServletResponse rsp) {
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		Double payMoney = placeService.getPayMoney(user, parkId);
		UserBalance balance = userService.getBalance(user.getId());
		JsonResult result = new JsonResult();
		Map map = new HashMap();
		
		map.put("payMoney", payMoney);
		map.put("balanceInfo",balance);
		result.setObj(map);
		rsp.setContentType("application/x-json;charset=UTF-8");
		return result.json();

	}
	
	@RequestMapping(value = "/mobile/rent/doExit.html")
	public ModelAndView doExit( Integer parkId,HttpServletRequest req) {
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		paymentService.doExit(user, parkId);
		ModelAndView view = new ModelAndView("forward:/mobile/rent/search.html");
		return view;

	}
	
	
	
	@RequestMapping(value = "/mobile/user/addPlate.html", method = RequestMethod.POST)
	public ModelAndView addPlate(String name, String plate, HttpServletRequest req) {
		ModelAndView view = null;
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		Integer useType = (Integer)req.getSession().getAttribute("useType");
		user.setName(name);
		user.setNickName(name);
		user.setPlate(plate);
		userService.updateUser(user);
		if(useType==0){
			view = new ModelAndView("forward:/mobile/rent/search.html");
		}else{
			view = new ModelAndView("forward:/mobile/user/myIncoming.html");
		}

		return view;
	}
	
	/**
	 * 我的收入
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/mobile/user/myIncoming.html")
	public ModelAndView myIncoming(HttpServletRequest req) {
		ModelAndView view = null;
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		List<Payment> list = paymentService.queryUser(user.getId(),false);
		view = new ModelAndView("/mobile/park/myIncoming.btl");
		view.addObject("list", list);
		return view;
	}
	
	/**
	 * 我的出租
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/mobile/user/myRent.html")
	public ModelAndView myRent(HttpServletRequest req,Integer parkId) {
		ModelAndView view = null;
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		//显示15天以内的情况
		List<PlaceRent> list = rentService.query(parkId, user.getId(), 15);
		view = new ModelAndView("/mobile/rent/myRent.btl");
		view.addObject("list", list);
		return view;
	}
	
	
	/**
	 * 更新出租信息
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/mobile/user/updateRent.html")
	public ModelAndView updateRent(HttpServletRequest req,Integer rentId,Integer parkId,String day,Integer status) {
		ModelAndView view = null;
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		rentService.updateRent(rentId, parkId, user.getId(), day, status);
		view = new ModelAndView("forward:/mobile/user/myRent.html");
		return view;
	}
	
	
	@RequestMapping(value = "/mobile/user/myPayment.html")
	public ModelAndView myPayment(HttpServletRequest req) {
		ModelAndView view = null;
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		List<Payment> list = paymentService.queryUser(user.getId(),true);
		view = new ModelAndView("/mobile/rent/myPayment.btl");
		view.addObject("list", list);
		return view;
	}
	/**
	 * 我的车位
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/mobile/user/myPlace.html")
	public ModelAndView myPlace(HttpServletRequest req) {
		ModelAndView view = null;
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		List<PlaceVo> list = placeService.getUserPlace(user.getId());
		view = new ModelAndView("/mobile/park/userPlace.btl");
		view.addObject("list", list);
		return view;
	}
	
	@RequestMapping(value = "/mobile/user/addPlacePage.html", method = RequestMethod.GET)
	public ModelAndView addPlacePage(HttpServletRequest req) {
		ModelAndView view = null;
		view = new ModelAndView("/mobile/park/addPlace.btl");
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		String loc = (String)req.getSession().getAttribute("location");
		Double[] locs = ParkUtil.getLoc(loc);
		List<Park> parks = searchService.search(locs[0], locs[1]);
		view.addObject("parks",parks);
		return view;
	}
	
	/**
	 * 添加车场，编辑车场
	 * @param place
	 * @param rule
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/mobile/user/editPlaceAction.html", method = RequestMethod.POST)
	public ModelAndView editPlaceAction(Place place,int rule,HttpServletRequest req) {
		ModelAndView view = null;
		
		SysUser user = (SysUser)req.getSession().getAttribute("user");
		place.setUserId(user.getId());
		placeService.addPlace(place);
		
		// 增加一条出租纪录,模拟情况下不考虑类型,实际上，应该时根据出租规则定时生成
		// 出租纪录
		
		PlaceRentRule rentRule = new PlaceRentRule();
		rentRule.setUserId(user.getId());
		rentRule.setType(rule);
		rentRule.setPlaceId(place.getId());
		
		carPlaceService.addPlaceRentRule(rentRule);
		
		if(rule==1){
			PlaceRent rent = new PlaceRent();
			rent.setDay(ParkUtil.today());
			rent.setOwnerId(user.getId());
			rent.setParkId(place.getParkId());
			rent.setRentType(rule);
			rent.setPlaceId(place.getId());
			rent.setStatus(0);
			carPlaceService.addPlaceRent(rent);
		}else if(rule==2){
			//job定时生成，为了演示方便，预先生成2个月的
			for(int i=0;i<60;i++){
				PlaceRent rent = new PlaceRent();
				rent.setDay(ParkUtil.getDay(i));
				rent.setOwnerId(user.getId());
				rent.setParkId(place.getParkId());
				rent.setRentType(rule);
				rent.setPlaceId(place.getId());
				rent.setStatus(0);
				carPlaceService.addPlaceRent(rent);
			}
		}
		
	
		
		view = new ModelAndView("forward:/mobile/user/myPlace.html");
		
		return view;
	}
	
	private void syncOrder(CarPlace cp){
		long id = cp.getId();
		int parkId = cp.getParkId();
		List<Gate>  list = gateService.getGates(parkId);
		for(Gate gate:list){
			String ip = gate.getIp();
			String code = gate.getCode();
			int status = 0;
			if(gate.getType()==1){
				status = 1;
			}else{
				//出口
				status = 2;
			}
			String orderParam = ParkUtil.gateInfo(id, status, code);
			HttpUtil.getNotify("http://"+ip+"/notify", "order="+orderParam);
		}
	}
	
	
	private void syncPay(CarPlace cp){
		long id = cp.getId();
		int parkId = cp.getParkId();
		List<Gate>  list = gateService.getGates(parkId);
		for(Gate gate:list){
			String ip = gate.getIp();
			String code = gate.getCode();
			int status = 0;
			if(gate.getType()==1){
				//不做处理了
				continue;
			}else{
				//出口,允许出厂
				status = 3;
			}
			String orderParam = ParkUtil.gateInfo(id, status, code);
			Long time = System.currentTimeMillis()/1000;
			String timeStr = Long.toHexString(time);
			HttpUtil.getNotify("http://"+ip+"/pay", "id="+orderParam+"&date="+timeStr);
		}
	}
	
	
	
	
}
